<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btnList="fullInfo.btnList"
        @returnBack="$emit('returnModify')"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.baseRef"
              :data="formInfo.data"
              :field-list="formInfo.baseInfoFieldList"
              :rules="formInfo.baseInfoRules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
              :image-field="formInfo.imageField"
            >
              <template v-slot:form-assetName>
                <el-input
                  v-model="formInfo.data.assetName"
                  class="not-mongolia"
                  type="input"
                  placeholder="请选择资产"
                  @blur="changeAsset"
                >
                  <template #append>
                    <el-icon @click="openAssetWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-deviceTypeValue>
                <el-input
                  v-model="formInfo.data.deviceTypeValue"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择医疗器械分类目录"
                >
                  <template #append>
                    <el-icon @click="openDeviceTypeWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-deptName>
                <el-input
                  v-model="formInfo.data.deptName"
                  type="input"
                  :disabled="true"
                  :class="'not-mongolia'"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openDeptList"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-deptManagerName>
                <el-input
                  v-model="formInfo.data.deptManagerName"
                  type="input"
                  :disabled="true"
                  :class="'not-mongolia'"
                  placeholder="请选择部门负责人"
                >
                  <template #append>
                    <el-icon @click="openUserList"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('main_use_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.mainUseRef"
              :data="formInfo.data"
              :field-list="formInfo.mainUseInfoFieldList"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('use_plan_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.usePlanRef"
              :data="formInfo.data"
              :field-list="formInfo.usePlanInfoFieldList"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('technical_parameter_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.technicalParameterRef"
              :data="formInfo.data"
              :field-list="formInfo.technicalParameterInfoFieldList"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('match_need_condition_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.matchNeedConditionRef"
              :data="formInfo.data"
              :field-list="formInfo.matchNeedConditionInfoFieldList"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('benefit_analysis_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.benefitAnalysisRef"
              :data="formInfo.data"
              :field-list="formInfo.benefitAnalysisInfoFieldList"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-frequency>
                <div class="flex" style="width: 600px">
                  <el-input-number
                    style="width: 50%"
                    controls-position="right"
                    :min="0"
                    :max="99999999"
                    placeholder=""
                    v-model="formInfo.data.useFrequency"
                    type="number"
                    class="flex-input"
                  >
                  </el-input-number>
                  <select-model
                    v-model="formInfo.data.frequencyUnit"
                    type-code="frequency_unit"
                    :clearable="false"
                    style="width: 15%"
                    class="flex-select"
                  />
                  <select-model
                    v-model="formInfo.data.frequencyCycle"
                    type-code="frequency_cycle"
                    :clearable="false"
                    style="width: 15%"
                    class="flex-select"
                  />
                </div>
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
    </div>

    <SelectUsers
      v-if="selectUserInfo.visible"
      v-model:showDialog="selectUserInfo.visible"
      :query="selectUserInfo.query"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectUserCallBack"
    />

    <select-setting-classification
      v-if="selectSettingClassificationInfo.visible"
      v-model:showDialog="selectSettingClassificationInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectSettingClassificationInfoCallBack"
    />

    <!--资产选择-->
    <select-equipment-archives
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="callBackEquipment"
    />
    <!--部门选择框-->
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDeptInfo.query"
      :save-empty="true"
      @callback="selectDeptCallBack"
    />
  </div>
</template>

<script setup name="assetApplicationModify">
import { getUnitAll } from '@/api/core'
import {
  createAssetApplication,
  createAssetApplicationAndSave,
  selectAssetApplicationById,
  updateAssetApplication,
} from '@/api/asset.js'
import { getRrgUserList } from '@/api/base.js'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id', 'type'])

const productionTimePickerOptions = ref({})
const selectUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {
    deptId: '',
  },
})
const selectSettingClassificationInfo = ref({
  visible: false,
  query: {
    status: '1',
  },
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {},
  },
})
const formInfo = ref({
  baseRef: null,
  mainUseRef: null,
  usePlanRef: null,
  technicalParameterRef: null,
  matchNeedConditionRef: null,
  benefitAnalysisRef: null,
  data: {
    qty: undefined,
    price: undefined,
    sumAmount: 0,
    frequencyUnit: '',
    frequencyCycle: '',
    preAssetName: '',
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
  },
  formDisabled: false,
  baseInfoFieldList: [
    {
      label: '申请标题',
      value: 'applicationTitle',
      type: 'input',
      required: true,
    },
    {
      label: '资产字典名称',
      value: 'assetName',
      type: 'slot',
      required: true,
    },
    {
      label: '资产字典编码',
      value: 'assetCode',
      placeholder: false,
      type: 'input',
      disabled: true,
    },
    {
      label: '医疗器械分类目录',
      value: 'deviceTypeValue',
      type: 'slot',
      disabled: true,
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '品牌',
      value: 'trademark',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '申请部门',
      value: 'deptName',
      type: 'slot',
      required: true,
    },
    {
      label: '部门负责人',
      value: 'deptManagerName',
      type: 'slot',
      required: true,
    },
    {
      label: '数量',
      value: 'qty',
      type: 'number',
      placeholder: false,
      min: 1,
      max: 99999999,
    },
    {
      label: '单价(预算/元)',
      value: 'price',
      type: 'number',
      placeholder: false,
      max: 99999999,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
    },
    {
      label: '总价',
      value: 'sumAmount',
      type: 'number',
      required: true,
      disabled: true,
      formatter: proxy.$fn.TripartiteMethodAsset,
      max: 999999999999,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
    },
    {
      label: '单位',
      value: 'unitId',
      type: 'select',
      required: true,
      list: 'unitList',
      filterable: true,
    },
    {
      label: '需求程度',
      value: 'needDegree',
      type: 'select-model',
      code: 'urgency_degree',
      required: true,
    },
    {
      label: '需求性质',
      value: 'needQuality',
      type: 'select-model',
      code: 'need_quality',
      required: true,
    },
    {
      label: '资金来源',
      value: 'capitalSourceId',
      type: 'select-model',
      code: 'asset_capital_source',
      required: true,
    },
    {
      label: '参考厂家',
      value: 'referenceBrand',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '参考型号',
      value: 'referenceStandard',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '参考品牌',
      value: 'referenceMark',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '是否首选进口产品',
      value: 'isFirstImport',
      type: 'radio-model',
      code: 'yes_or_no',
    },
  ],
  baseInfoRules: {
    assetName: [
      {
        required: true,
        message: '请输入资产名称',
        trigger: 'blur',
      },
    ],
    applicationTitle: [
      {
        required: true,
        message: '请输入申请标题',
        trigger: 'blur',
      },
    ],
    deptName: [{ required: true, message: '请输入部门', trigger: 'blur' }],
    productType: [
      {
        required: true,
        message: '请选择产品类型',
        trigger: 'change',
      },
    ],
    qty: [
      {
        required: true,
        message: '请输入数量',
        trigger: 'blur',
      },
    ],
    unitId: [
      {
        required: true,
        message: '请选择单位',
        trigger: 'change',
      },
    ],
    price: [
      {
        required: true,
        message: '请输入单价',
        trigger: 'blur',
      },
    ],
    needDegree: [
      {
        required: true,
        message: '请选择需求程度',
        trigger: 'change',
      },
    ],
    needQuality: [
      {
        required: true,
        message: '请选择需求性质',
        trigger: 'change',
      },
    ],
    capitalSource: [
      {
        required: true,
        message: '请选择资金来源',
        trigger: 'change',
      },
    ],
  },
  mainUseInfoFieldList: [
    {
      label: '资产主要用途',
      value: 'mainUse',
      type: 'textarea',
      className: 'not-br',
    },
  ],
  usePlanInfoFieldList: [
    {
      label: '采购后使用规划',
      value: 'usePlan',
      type: 'textarea',
      className: 'not-br',
    },
  ],
  technicalParameterInfoFieldList: [
    {
      label: '具体配置及技术参数',
      value: 'technicalParameter',
      type: 'textarea',
      className: 'not-br',
    },
  ],
  matchNeedConditionInfoFieldList: [
    {
      label: '场所是否符合要求',
      value: 'isFitPlace',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '水电配置要求',
      value: 'hydropowerDemand',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '污染排放问题及解决措施',
      value: 'pollutionDischargeMeasures',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '科室人员配备、培训情况',
      value: 'trainSituation',
      labelTip: '能否保证仪器资产正常运行',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '是否需要技术申报',
      labelTip: '如有请注明申报情况',
      value: 'needSkillDeclare',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '是否涉及专项经费使用',
      labelTip: '如有请注明经费名称',
      value: 'specialOutlay',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '其他特殊要求',
      value: 'otherDemand',
      type: 'input',
      maxlength: 100,
    },
  ],
  benefitAnalysisInfoFieldList: [
    {
      label: '预计使用人次',
      value: 'frequency',
      type: 'slot',
      maxlength: 3000,
      className: 'not-br',
    },
    {
      label: '开展项目及收费清单',
      value: 'itemChargeList',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '所需耗材清单',
      value: 'needMaterialList',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '平均人次耗材成本(元)',
      value: 'averageMaterialCost',
      type: 'number',
      required: true,
      placeholder: false,
      max: 99999999,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
    },
    {
      label: '预计每年维修保养成本(元)',
      value: 'annualMaintenanceCost',
      type: 'number',
      required: true,
      placeholder: false,
      max: 99999999,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
    },
    {
      label: '预计年收入(元)',
      value: 'annualIncome',
      type: 'number',
      required: true,
      placeholder: false,
      max: 99999999,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
    },
    {
      label: '计划启用时间',
      value: 'planUseTime',
      type: 'date',
      placeholder: false,
    },
  ],
  labelWidth: '120px',
})
const listTypeInfo = ref({
  unitList: [],
})
const options = ref([])
const fullInfo = ref({
  btnList: [
    { label: '保存并提交', event: saveAndSubmit, show: !props.id && proxy.$permission('assetApplication:saveAndSubmit') },
    { label: '保存', event: save, show: true }
  ],
})
const flag = ref(true)
const deptId = ref(undefined)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => formInfo.value.data,
  (val) => {
    if (val) {
      let sumAmount = proxy.$fn.accMul(val.qty || 0, parseFloat(val.price || 0))
      val['sumAmount'] = sumAmount
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  getUnitList()
  if (props.id) {
    getDetails()
  }
})
function handleResponse(response) {
  return response
}
//获取计量单位列表
function getUnitList() {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
function openUserList() {
  selectUserInfo.value.query.deptId = formInfo.value.data.deptId
  selectUserInfo.value.visible = true
}
function selectUserCallBack(row) {
  if (row) {
    formInfo.value.data['deptManager'] = row.id
    formInfo.value.data['deptManagerName'] = row.name
  } else {
    formInfo.value.data['deptManager'] = ''
    formInfo.value.data['deptManagerName'] = ''
  }
}
function openDeptList() {
  if (deptId.value) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请先选择部门!',
    })
    return
  }
  selectDeptInfo.value.visible = true
}
function selectDeptCallBack(row) {
  if (row) {
    formInfo.value.data['deptId'] = row.id
    formInfo.value.data['deptName'] = row.name

    formInfo.value.data['deptManager'] = row.managerUserId
    formInfo.value.data['deptManagerName'] = row.managerUserName
  } else {
    formInfo.value.data['deptId'] = ''
    formInfo.value.data['deptName'] = ''

    formInfo.value.data['deptManager'] = ''
    formInfo.value.data['deptManagerName'] = ''
  }
}
function selectSettingClassificationInfoCallBack(row) {
  if (row) {
    formInfo.value.data['deviceType'] = row.id
    formInfo.value.data['deviceTypeValue'] = row.name
  } else {
    formInfo.value.data['deviceType'] = '-2'
    formInfo.value.data['deviceTypeValue'] = ''
  }
}
function callBackEquipment(row) {
  if (row) {
    formInfo.value.data['productId'] = row.id
    formInfo.value.data['assetName'] = row.commonName
    formInfo.value.data['preAssetName'] = row.commonName
    formInfo.value.data['assetCode'] = row.code
    formInfo.value.data['deviceType'] = row.deviceType
    formInfo.value.data['deviceTypeValue'] = row.deviceTypeValue
    formInfo.value.data['standard'] = row.standard
    formInfo.value.data['trademark'] = row.trademark
    if (row.unitId && row.unitId != -2) {
      formInfo.value.data['unitId'] = row.unitId
      formInfo.value.data['unitName'] = row.unitName
    } else {
      formInfo.value.data['unitId'] = ''
      formInfo.value.data['unitName'] = ''
      setTimeout(() => {
        formInfo.value.baseRef.clearValidate('unitId')
      }, 30)
    }
  }
}
function openDeviceTypeWindow() {
  selectSettingClassificationInfo.value.visible = true
}
function openAssetWindow() {
  selectAssetInfo.value.visible = true
}
function changeAsset() {
  if (formInfo.value.data.preAssetName !== formInfo.value.data.assetName) {
    formInfo.value.data['productId'] = undefined
    formInfo.value.data['assetCode'] = ''
  }
}
function getDetails() {
  selectAssetApplicationById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  formInfo.value.baseRef.validate((valid) => {
    if (valid) {
      let api = formInfo.value.data.id
        ? updateAssetApplication
        : isSaveAndSubmit === true ? createAssetApplicationAndSave : createAssetApplication
      api(formInfo.value.data).then((resp) => {
        if (resp && resp.success) {
          emits('returnModify', true)
          showDialog.value = false
        }
      })
    }
  })
}
</script>

<style scoped>
.flex {
  display: flex;
  flex: 1;
}
.flex-select :deep(.el-input--small) .el-input__inner {
  height: 28px !important;
}
</style>
